<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ page import="nc.itf.uap.busibean.ISysInitQry" %>
<%@ page import="nc.sso.bs.RandomUtils" %>
<%@ page import="nc.bs.framework.common.NCLocator" %>
<%@ page import="nc.bs.framework.session.WebSession" %>
<%@ page import="nc.bs.framework.session.SessionContext" %>
<%@ page import="nc.bs.framework.server.ISecurityTokenCallback" %>

<%@ page import="ncc.sso.bs.NCCSSORegInfo" %>
<%@ page import="ncc.sso.bs.INCCSSOService" %>

<%@ page import="nccloud.framework.service.ServiceLocator" %>
<%@ page import="nccloud.framework.web.container.HttpOperator" %>
<%@ page import="nccloud.framework.web.container.NCCLoudSession" %>

<%@ page import="com.yonyou.chuan.log.LoggerUtil" %>
<%@ page import="com.yonyou.chuan.model.param.NxQxgParam" %>
<%@ page import="com.yonyou.chuan.service.YhtPubService" %>
<%@ page import="com.yonyou.chuan.model.vo.YhtUserVO" %>

<%@ page import="cn.hutool.http.HttpUtil" %>
<%@ page import="cn.hutool.json.JSONUtil" %>
<%@ page import="cn.hutool.crypto.SecureUtil" %>

<html>
<head>
	<title>单点登陆</title>
	<!-- @date          2024-09-26 -->
	<!-- @author        wangmob -->
	<!-- @discription   中能北气7小哥聚合平台单点登陆,支持挤掉上一个登陆人,支持会话同人免登 -->
	<!-- @demo1			http://127.0.0.1:8088/nccloud/html/login.jsp?target=/nccloud/resources/workbench/public/common/main/index.html -->
	<!-- @demo2			http://127.0.0.1:8088/nccloud/html/login.jsp?target=/nccloud/resources/workbench/public/common/main/index.html#/ifr?ifr=%252Fnccloud%252Fresources%252Fuap%252Fmsgcenter%252Fmessage%252Fmain%252Findex.html&c=10160501&p=10160501APPROVE&ar=0001Z0100000000042SD&n=%25E5%25AE%25A1%25E6%2589%25B9%25E4%25B8%25AD%25E5%25BF%2583&b1=%25E5%258A%25A8%25E6%2580%2581%25E5%25BB%25BA%25E6%25A8%25A1%25E5%25B9%25B3%25E5%258F%25B0&b2=%25E6%25B5%2581%25E7%25A8%258B%25E7%25AE%25A1%25E7%2590%2586&b3=%25E5%25AE%25A1%25E6%2589%25B9%25E7%25AE%25A1%25E7%2590%2586 -->
	<!-- Jsp内置对象System,request,response,session,out -->
	<!-- 不要奇怪为什么用NCLocator,因为有的接口ServiceLocator lookup不到 -->
</head>

<style>
	*{margin:0;padding:0}body{width:100%;height:100%;color:#6A6A6B;font-family:"Microsoft YaHei"}.unsupport-container{width:1200px;height:600px;position:absolute;left:50%;top:50%;margin-left:-400px;margin-top:-200px}.unsupport-msg{width:600px;margin-left:30px}.unsupport-container>div{float:left}.unsupport-image{width:344px;height:221px}.unsupport-image img{width:100%;height:100%}.unsupport-head-msg{font-size:30px}.unsupport-bottom-msg{font-size:18px;color:#252A36}.download-button{margin-top:95px}.download-button button{}.download-button a{display:inline-block;line-height:40px;text-decoration:none;color:#FFFFFF;font-size:14px;width:130px;height:40px;background:#E73D36;border:none;border-radius:3px;text-align:center}.prompt-msg{font-size:15px;color:#717171;margin-top:12px}
</style>

<body>
<div class="unsupport-container">
	<div class="unsupport-image">
		<img src="./html/image/browser_support.png">
	</div>
	<div class="unsupport-msg">
		<p class="unsupport-head-msg">登陆出错啦</p>
		<p class="unsupport-bottom-msg">
			<%
				try{
					long timestamp = System.currentTimeMillis();	// 时间戳
					String GLOBE_ORG = "GLOBLE00000000000000";      // 业务参数全局
					ServiceLocator.find(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());//模拟登录
					ISysInitQry sysInit = ServiceLocator.find(ISysInitQry.class);
					YhtPubService yhtService = ServiceLocator.find(YhtPubService.class);
					String Oringin = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-执行】: {}", timestamp);
					String ticket = request.getParameter("ticket");
					String target = request.getParameter("target");
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-票据】ticket: {}", ticket);
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-目标】target: {}", target);
					String realPath = (target != null && target.length() > 0) ? new String(java.util.Base64.getUrlDecoder().decode(target)) : Oringin;
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-目标】realPath: {}", target);

					String VerifyPath_Ww = sysInit.getParaString(GLOBE_ORG, "qxg_verify_internet");             //7小哥认证中心地址外网

					if(ticket == null || ticket.isEmpty()){
						String path = java.util.Base64.getUrlEncoder().encodeToString(realPath.getBytes());
						target = String.format(VerifyPath_Ww + NxQxgParam.authApi, java.net.URLEncoder.encode(request.getRequestURL() + "?target=" + path, "UTF-8"));
						LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-票据不存在】,执行跳转: {}", target);
						response.sendRedirect(target);
						return;
					}
					//TODO 业务参数注入
					String VerifyPath_Nw = sysInit.getParaString(GLOBE_ORG, "qxg_verify");    					//7小哥认证中心地址内网
					String qxg_secretKey = sysInit.getParaString(GLOBE_ORG, "qxg_secretKey");          			//7小哥认证秘钥

					//TODO LoginId
					String ticketPath = String.format(VerifyPath_Nw + NxQxgParam.ticketApi,ticket);
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-ticket验票】,请求地址: {}",ticketPath);
					String resp1 = HttpUtil.createPost(ticketPath).execute().body();
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-ticket验票】,响应报文: {}",resp1);
					String loginId = JSONUtil.parseObj(resp1).getStr("data");
					if(loginId == null || loginId.isEmpty()){
						out.println("ticket-verify-error: " + resp1);
						return;
					}
					//TODO staffId
					String nonce = RandomUtils.genRandomNumber(20, ""); 										// 随机字符串
					String apiType = "userInfo";
					String sign = SecureUtil.md5("apiType=" + apiType + "&loginId=" + loginId + "&nonce=" + nonce + "&timestamp=" + timestamp + "&key=" + qxg_secretKey);
					String fullPath = String.format(VerifyPath_Nw + NxQxgParam.userInfoApi,apiType,loginId,timestamp,nonce,sign);
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-LoginId用户】,请求地址: {}",fullPath);
					String resp2 = HttpUtil.createPost(fullPath).execute().body();
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-LoginId用户】,响应报文: {}",resp2);
					String staffId = JSONUtil.parseObj(resp2).getStr("nccUserId");
					if(staffId == null || staffId.isEmpty()){
						out.println("loginId-verify-error: " + resp2);
						return;
					}
					// TODO 转换yht用户
					YhtUserVO yhtUserVO = yhtService.queryByStaffId(staffId);
					if(yhtUserVO == null){
						out.println("yhtUserVO-verify-error: user not found by" + staffId);
						return;
					}
					// TODO 校验登陆状态
					HttpOperator httpOperator = HttpOperator.getInstance();
					httpOperator.bind(request, response);
					NCCLoudSession nccSession = NCCLoudSession.getInstance();
					nccSession.bindReq(httpOperator.getRequest());
					String sessionId = nccSession.getCookieValue(NCCLoudSession.NCCloudSessionID);
					if (sessionId != null && sessionId.length() > 0) {
						WebSession websession = SessionContext.getSession(sessionId);
						if(websession != null){
							String userid = websession.getValue("userid");
							if(userid != null && userid.equals(yhtUserVO.getUserId())){
								LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-直接登录】userid: {} ,username: {} ,isLogin : {}",userid,yhtUserVO.getUserName(),true);
								LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-Nccloud登录】,执行跳转: {}", realPath);
								response.sendRedirect(realPath);
								return;
							}
							else
							{
								LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-踢人下线】userid: {} ,username: {} ,doLoginout : {}",userid,yhtUserVO.getUserName(),true);
								SessionContext.removeSession(sessionId); // TODO Loginout
							}
						}
					}
					// TODO 注册令牌
					NCCSSORegInfo ssoInfo = new NCCSSORegInfo();
					ssoInfo.setUsercode(yhtUserVO.getUserCode());
					ssoInfo.setLangCode("simpchn");
					ssoInfo.setBusiCenterCode("nccpro");														//账套编码
					ssoInfo.setAccess_token(nonce);
					NCLocator.getInstance().lookup(INCCSSOService.class).registerSSOInfo(ssoInfo);
					// TODO 重定向
					String finalPath = String.format(Oringin + "/nccloud/resources/uap/rbac/thirdpartylogin/main/index.html" + "?accesstoken=%s&redirect_uri=%s",nonce,realPath);
					LoggerUtil.printLogger("【7小哥聚合平台系统过滤器-Nccloud登录】,执行跳转: {}", finalPath);
					response.sendRedirect(finalPath);
				} catch (Exception e) {
					out.println(e.getMessage());
				}
			%>
		</p>
	</div>
</div>
</body>
</html>